import 'package:flutter/material.dart';
import 'widgets/counter_display.dart';

class CounterScreen extends StatefulWidget {
  const CounterScreen({super.key});
  @override
  State<CounterScreen> createState() => _CounterScreenState();
}

class _CounterScreenState extends State<CounterScreen> {
  int _counter = 0;
  late final ValueNotifier<int> _secretCounter;

  @override
  void initState() {
    super.initState();
    print("🚀 initState() - 初始化状态");

    // 模拟从持久化存储加载数据
    Future.delayed(Duration.zero, () {
      final saveCount = _loadSavedCount();
      setState(() => _counter = saveCount);
    });

    // 初始化其他状态对象
    _secretCounter = ValueNotifier(100);
  } //  演示状态分离

  // 模拟加载保存的计数器值
  int _loadSavedCount() {
    print("📥 从模拟存储加载数据...");
    return 5; //默认值
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("🔄 didChangeDependencies() - 依赖变化");
  }


  @override
  void didUpdateWidget(covariant CounterScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("🆙 didUpdateWidget() - 组件更新");
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
      _secretCounter.value += 2; //独立更新
    });
    print("➕ 计数器增加: $_counter");
  }

  void _resetCounter() {
    setState(() => _counter = 0);
    print("🔄 计数器重置");
  }

  @override
  Widget build(BuildContext context) {
    print("🏗️ build() - 构建界面");
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter计数器'),
        actions: [
          IconButton(icon: const Icon(Icons.refresh), onPressed: _resetCounter)
        ],
      ),
      body: Center(
        child: Column(mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 主计数器显示
            CounterDisplay(count: _counter),
            const SizedBox(height: 30),
            // 独立状态计数器
            ValueListenableBuilder(valueListenable: _secretCounter,
                builder: (_, secretCount, __) {
                  return Text('隐藏计数器: $secretCount',
                    style: const TextStyle(color: Colors.grey),
                  );
                }),
            const SizedBox(height: 20),
            Text('状态类型: ${_counter.isEven ? "偶数" : "奇数"}',
              style: TextStyle(
                  color: _counter.isEven ? Colors.green : Colors.red,
                  fontWeight: FontWeight.bold
              ),)
          ],),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '增加',
        child: const Icon(Icons.add),
      ),
    );
  }

  @override
  void deactivate() {
    print("⚠️ deactivate() - 组件停用");
    super.deactivate();
  }

  @override
  void dispose() {
    print("♻️ dispose() - 资源释放");
    _secretCounter.dispose(); // 必须释放！
    super.dispose();
  }

}

